package dk.ucn.datamatiker.henrik.bundtkage.earthcake.albeheweather;

import java.io.IOException;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class SelectLocationActivity extends Activity {

	private final static String LOG = "AlBeHeWeather";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_select_location);
			TextView currentLocationView = (TextView) findViewById(R.id.currentLocationView);

			if (States.getInstance().getCurrentLocation() != null) {
				currentLocationView.setText("Current Location: "
						+ States.getInstance().getCurrentLocation()
								.getDescription());
			} else {
				currentLocationView
						.setText("You have not selected a location yet");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.select_location, menu);
		return true;
	}

	public void onClick(View v) throws IOException, XmlPullParserException {
		setLocations();
		Intent intent = new Intent(this, LocationsListActivity.class);
		startActivity(intent);
		Log.d(LOG, "onClick clicked");
	}

	private void setLocations() throws IOException, XmlPullParserException {
		EditText locationBox = (EditText) findViewById(R.id.locationText);
		String locationString = locationBox.getText().toString();

		InputStream inputStream = Downloader.getInstance().downloadInputStream(
				getString(R.string.search_location) + locationString);
		Parser parser = new Parser();
		XmlPullParser parser2 = parser.parse(inputStream);
		States.getInstance().setLocations(parser.readLocationsFeed(parser2));
	}

}
